package net.avcompris.binding.yaml.impl;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;

import javax.xml.parsers.ParserConfigurationException;

import net.avcompris.binding.BindConfiguration;
import net.avcompris.binding.dom.DomBinder;
import net.avcompris.binding.dom.impl.DefaultDomBinder;
import net.avcompris.binding.impl.AbstractBinder;
import net.avcompris.binding.yaml.YamlBinder;

import org.w3c.dom.Node;

/**
 * default implementation of {@link YamlBinder} by use of the <tt>avc-binding-dom</tt> toolset:
 * First we transform the YAML incoming stream into a DOM node, then we bind it to Java proxies.
 *
 * @author David Andrianavalontsalama
 */
public class DomYamlBinder extends AbstractBinder<Object> implements YamlBinder {

	@Override
	protected <T> T bindInterface(final BindConfiguration configuration,
			final Object yaml, final ClassLoader classLoader,
			final Class<T> clazz) {

		nonNullArgument(clazz, "clazz");
		nonNullArgument(yaml, "yaml");
		nonNullArgument(configuration, "configuration");
		nonNullArgument(classLoader, "classLoader");

		final Node node;

		try {

			node = DomYamlConverter.yamlToNode(yaml, configuration);
			
 		} catch (final ParserConfigurationException e) {

			throw new DomYamlConversionException(
					"Cannot convert YAML stream to DOM node", e);
		}

		final DomBinder domBinder = new DefaultDomBinder();

		return domBinder.bind(configuration, node, classLoader, clazz);
	}
}
